from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from . import models, database
from pydantic import BaseModel

router = APIRouter()


class CartItemBase(BaseModel):
    product_id: int
    quantity: int


class CartItemCreate(CartItemBase):
    pass


class CartItem(CartItemBase):
    id: int
    cart_id: int

    class Config:
        orm_mode = True


class Cart(BaseModel):
    id: int
    user_id: int
    items: List[CartItem] = []

    class Config:
        orm_mode = True


@router.post("/carts/{user_id}/items/", response_model=CartItem)
def add_to_cart(user_id: int, item: CartItemCreate, db: Session = Depends(database.get_db)):
    # 获取或创建用户的购物车
    cart = db.query(models.Cart).filter(models.Cart.user_id == user_id).first()
    if not cart:
        cart = models.Cart(user_id=user_id)
        db.add(cart)
        db.commit()
        db.refresh(cart)

    # 检查商品是否存在
    product = db.query(models.Product).filter(
        models.Product.id == item.product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="Product not found")

    # 检查库存
    if product.stock < item.quantity:
        raise HTTPException(status_code=400, detail="Not enough stock")

    # 创建购物车项
    cart_item = models.CartItem(cart_id=cart.id, **item.dict())
    db.add(cart_item)
    db.commit()
    db.refresh(cart_item)
    return cart_item


@router.get("/carts/{user_id}", response_model=Cart)
def get_cart(user_id: int, db: Session = Depends(database.get_db)):
    cart = db.query(models.Cart).filter(models.Cart.user_id == user_id).first()
    if not cart:
        cart = models.Cart(user_id=user_id)
        db.add(cart)
        db.commit()
        db.refresh(cart)
    return cart


@router.delete("/carts/{user_id}/items/{item_id}")
def remove_from_cart(user_id: int, item_id: int, db: Session = Depends(database.get_db)):
    cart = db.query(models.Cart).filter(models.Cart.user_id == user_id).first()
    if not cart:
        raise HTTPException(status_code=404, detail="Cart not found")

    cart_item = db.query(models.CartItem).filter(
        models.CartItem.id == item_id,
        models.CartItem.cart_id == cart.id
    ).first()

    if not cart_item:
        raise HTTPException(status_code=404, detail="Item not found in cart")

    db.delete(cart_item)
    db.commit()
    return {"message": "Item removed from cart"}
